/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author binh
 */
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

//import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
//import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

// De chay Appletviewer can phai co dong comment sau day
// <APPLET CODE="WriteFile.class" WIDTH="350" HEIGHT="100"> </APPLET>

public class WriteFile extends Applet implements ActionListener{
    JLabel lb1, lb2;
    JTextField txtCode, txtName;
    JButton btnSave, btnClear;

    public void init()
    {
        lb1 = new JLabel("Student Code");
        lb2 = new JLabel("Student Name");
        txtCode = new JTextField(20);
        txtName = new JTextField(20);
        btnSave = new JButton("SAVE");
        btnClear = new JButton("CLEAR");
        setLayout(new FlowLayout());
        this.add(lb1);
        this.add(txtCode);
        this.add(lb2);
        this.add(txtName);
        this.add(btnSave);
        btnSave.addActionListener(this);
        this.add(btnClear);
        btnClear.addActionListener(this);
    }

     public void saveState() {
        try {
            FileWriter fwriter = new FileWriter("Account.txt", true);
            BufferedWriter writer = new BufferedWriter(fwriter);
            writer.write(this.txtCode.getText());
            writer.write("\t");
            writer.write(this.txtName.getText());
            writer.write("\t");
            writer.newLine();
            writer.close();
            fwriter.close();
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, "The requested file cannot be found.");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "An error occurred while writing to the file.");
        }
    }
    public void actionPerformed(ActionEvent ex)
    {
        //JOptionPane.showMessageDialog(null, "This is a program for writing file");
        if(ex.getSource().equals(btnSave)){
        	this.saveState();
        }
        else if (ex.getSource().equals(btnClear)){
        	this.txtCode.setText("");
        	this.txtName.setText("");
        }
        
    }
}
